package com.yeyks.util;

import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    private static final HashFunction MD5 = Hashing.md5();
    public static String encode(CharSequence rawPassword) {
        return MD5.newHasher().putString(rawPassword, Charsets.UTF_8).hash().toString();
    }

    public static String encode(CharSequence rawPassword, String charset) {
        return MD5.newHasher().putString(rawPassword, Charset.forName(charset)).hash().toString();
    }

    public static boolean matches(CharSequence rawPassword, String encodedPassword) {
        String rawEncoded;
        rawEncoded = MD5.newHasher().putString(rawPassword, Charsets.UTF_8).hash().toString();
        return encodedPassword.equalsIgnoreCase(rawEncoded);
    }

    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.err.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuilder md5StrBuff = new StringBuilder();

        for (byte aByteArray : byteArray) {
            if (Integer.toHexString(0xFF & aByteArray).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & aByteArray));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & aByteArray));
            }
        }

        return md5StrBuff.toString();
    }
}
